<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标签名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入标签名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>



    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['article:label:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['article:label:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
           :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['article:label:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>



<!--外层表格-->
    <el-table v-loading="loading" :data="labelList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="标签id" align="center" prop="id" />
      <el-table-column label="标签名称" align="center" prop="name" />
      <el-table-column label="所属文章" align="center" prop="articleName" >
        <template #default="scope">
          <el-button type="success" plain @click="dialogArticle(scope.row)">
            查看文章
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="标签状态" align="center" width="100">
        <template #default="scope">
          <el-switch
              v-model="scope.row.isStart"
              active-value="0"
              inactive-value="1"
              @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['article:label:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['article:label:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
<!--    外层分页-->
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改标签按钮 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="labelRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标签名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入标签名称"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <!--查看文章按钮-->
    <el-dialog v-model="dialogTableVisible" :title="articleTitle"  center width="950">
      <div>
        <el-form :model="articleQueryParams"   ref="articleQueryRef" :inline="true" v-show="showSearch" >
          <el-form-item label="文章标题" prop="title">
            <el-input
                v-model="articleQueryParams.title"
                placeholder="请输入文章标题"
                @keyup.enter="articleHandleQuery"
            />
          </el-form-item>

          <el-form-item label="发布时间" prop="sendTime">
            <el-date-picker clearable
                            v-model="articleQueryParams.sendTime"
                            type="date"
                            value-format="YYYY-MM-DD"
                            placeholder="请选择文章发布时间">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="文章状态" prop="status">
            <el-select v-model="articleQueryParams.status"  clearable style="width: 196px">
              <el-option
                  v-for="dict in article_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="Search" @click="articleHandleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="articleResetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table :data="gridData">
        <el-table-column prop="title" label="文章"  align="center" />
        <el-table-column prop="author" label="作者"  align="center" />
        <el-table-column  prop="sendTime" label="发布时间" align="center" >
          <template #default="scope">
           <span style="color: red" v-if="scope.row.sendTime == null">待发布</span>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          class="my-pagination"
          v-model:current-page="articleQueryParams.pageNum"
          v-model:page-size="articleQueryParams.pageSize"
          :page-sizes="[2, 4, 6, 8]"
          size="default"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="articleTotal"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </el-dialog>



  </div>
</template>

<script setup name="Label" >
import { listLabel, getLabel, delLabel, addLabel, updateLabel } from "@/api/article/label";
import {listArticle} from "@/api/article/article.js";

const { proxy } = getCurrentInstance();
const { label_status,article_status } = proxy.useDict("label_status","article_status");
const dialogTableVisible = ref(false)
const labelList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const articleTotal = ref(0);
const title = ref("");
const articleTitle = ref("")

const background = ref(false)
const disabled = ref(false)
const gridData = ref([])
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    isStart: null,
  },
  rules: {
  },
  articleQueryParams: {
    pageNum: 1,
    pageSize: 2,
    title:null,
    sendTime:null,
    status:null,
    labelId:null,
  },

});



const { queryParams, form, rules,articleQueryParams } = toRefs(data);


/**分页查询*/
const handleSizeChange = (val) => {
  articleQueryParams.pageSize = val
  getArticleList()
  console.log(`${val} items per page`)
}
const handleCurrentChange = (val) => {
  articleQueryParams.pageNum = val
  getArticleList()
  console.log(`current page: ${val}`)
}
/**显示所属文章列表*/
function dialogArticle(row){
  dialogTableVisible.value = true
  articleTitle.value = row.name+'标签所属文章'
  articleQueryParams.value.labelId = row.id
  getArticleList()
}

/** 文章搜索按钮操作 */
function articleHandleQuery() {
  articleQueryParams.value.pageNum = 1;
  getArticleList();
}

/** 查询文章列表 */
function getArticleList() {
  listArticle(articleQueryParams.value).then(response => {
    gridData.value = response.rows;
    articleTotal.value = response.total
  });
}
/** 查询标签列表 */
function getList() {
  loading.value = true;
  listLabel(queryParams.value).then(response => {
    labelList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    isStart: null,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("labelRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 重置标签下文章按钮操作 */
function articleResetQuery() {
  proxy.resetForm("articleQueryRef");
  articleHandleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加标签";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getLabel(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改标签";
  });
}

/** 标签状态修改 */
function handleStatusChange(row) {
  let text = row.isStart === "0" ? "启用" : "禁用";
  console.log(row,"@@@@")
  proxy.$modal.confirm('确认要"' + text + '""' + row.name + '"标签吗?').then(function () {
    updateLabel(row).then(response => {
      getList();
    });
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功");
  }).catch(function () {
    row.isStart = row.isStart === "0" ? "1" : "0";
  });
}


/** 提交按钮 */
function submitForm() {
  proxy.$refs["labelRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateLabel(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addLabel(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除标签编号为"' + _ids + '"的数据项？').then(function() {
    return delLabel(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('article/label/export', {
    ...queryParams.value
  }, `label_${new Date().getTime()}.xlsx`)
}

getList();
</script>
<style scoped>

.my-pagination{
  margin-top: 25px;
  display: flex;
  justify-content: center;
}
</style>